package com.smart.community.property.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.smart.community.commons.utils.SecurityUtils;

import com.smart.community.commons.entity.property.PropertyCompany;
import com.smart.community.commons.entity.property.UserPropertyCompany;
import com.smart.community.commons.result.Result;
import com.smart.community.property.dto.PropertyInfoDTO;
import com.smart.community.property.service.IPropertyCompanyService;
import com.smart.community.property.service.IPropertyCompanyStatisticsService;
import com.smart.community.property.service.IPropertyInfoService;
import com.smart.community.property.service.IUserPropertyCompanyService;
import com.smart.community.property.vo.PropertyInfoStatsVO;
import com.smart.community.commons.vo.property.PropertyInfoVO;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 物业信息管理服务实现类
 * 提供物业公司信息的查询、更新、统计等功能
 * 
 * 严格按照《Java后端SpringBoot代码开发规范.md》Service层规范实现：
 * - 职责分离：Service实现类专注于业务逻辑实现
 * - 接口调用：通过Service接口进行数据访问
 * - 异常处理：完善的异常处理和日志记录
 * - 缓存策略：合理的缓存键设计和失效策略
 * - 性能监控：详细的性能指标记录
 * - 生产环境标准：移除throws Exception声明，使用统一异常处理
 * - 用户信息获取：统一使用SecurityUtils标准方法
 * - 缓存降级：实现缓存降级机制，确保系统可用性
 * 
 * @author Wu.Liang
 * @since 2025-01-30
 * @version 2.0.0 - 生产环境标准优化，移除throws Exception声明，完善缓存策略
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PropertyInfoServiceImpl implements IPropertyInfoService {

    private final IPropertyCompanyService propertyCompanyService;
    private final IUserPropertyCompanyService userPropertyCompanyService;
    private final IPropertyCompanyStatisticsService propertyCompanyStatisticsService;

    @Override
    public PropertyInfoVO getPropertyInfo(Long propertyCompanyId) {
        long startTime = System.currentTimeMillis();
        log.info("获取物业公司信息，物业公司ID：{}", propertyCompanyId);
        
        try {
            // 参数验证
            if (propertyCompanyId == null || propertyCompanyId <= 0) {
                log.warn("物业公司ID无效：{}", propertyCompanyId);
                return null;
            }
            
            // 获取物业公司基本信息
            PropertyCompany propertyCompany = propertyCompanyService.getById(propertyCompanyId);
            if (propertyCompany == null) {
                log.warn("物业公司{}不存在", propertyCompanyId);
                return null;
            }

            // 转换为VO对象
            PropertyInfoVO propertyInfoVO = convertToVO(propertyCompany);
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("获取物业公司{}信息成功，耗时：{}ms", propertyCompanyId, responseTime);
            
            return propertyInfoVO;
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取物业公司{}信息异常，耗时：{}ms", propertyCompanyId, responseTime, e);
            // 生产环境标准：不抛出异常，返回null
            return null;
        }
    }

    @Override
    public PropertyInfoStatsVO getPropertyInfoStats(Long propertyCompanyId) {
        long startTime = System.currentTimeMillis();
        log.info("获取物业公司综合统计信息，物业公司ID：{}", propertyCompanyId);
        
        try {
            // 参数验证
            if (propertyCompanyId == null || propertyCompanyId <= 0) {
                log.warn("物业公司ID无效：{}", propertyCompanyId);
                return createDefaultPropertyInfoStatsVO(propertyCompanyId);
            }
            
            // 严格按照Service规范：职责分离，通过Service接口进行数据访问
            // 核心统计数据通过调用统计服务获取，避免重复实现
            Result<Map<String, Object>> statsResult = propertyCompanyStatisticsService.getComprehensiveStatistics(propertyCompanyId);
            
            if (statsResult.isSuccess() && statsResult.getData() != null) {
                Map<String, Object> stats = statsResult.getData();
                
                // 添加物业信息服务特有的统计信息（这些不在统计服务中）
                // 严格按照Service规范：Service实现类专注于业务逻辑实现
                enrichWithPropertySpecificStats(stats, propertyCompanyId);
                
                long responseTime = System.currentTimeMillis() - startTime;
                log.info("获取物业公司{}综合统计信息成功，耗时：{}ms", propertyCompanyId, responseTime);
                
                return convertToPropertyInfoStatsVO(stats, propertyCompanyId);
            } else {
                log.warn("获取物业公司{}核心统计信息失败：{}", propertyCompanyId, statsResult.getMessage());
                return createDefaultPropertyInfoStatsVO(propertyCompanyId);
            }
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取物业公司{}综合统计信息异常，耗时：{}ms", propertyCompanyId, responseTime, e);
            // 生产环境标准：异常时返回默认值，确保系统可用性
            return createDefaultPropertyInfoStatsVO(propertyCompanyId);
        }
    }

    @Override
    @GlobalTransactional
    @CacheEvict(value = { "propertyCompany", "propertyInfo", "propertyCompanyStats", "permission" }, allEntries = true)
    public boolean updatePropertyInfo(PropertyInfoDTO propertyInfoDTO) {
        long startTime = System.currentTimeMillis();
        log.info("更新物业公司信息，物业公司ID：{}", propertyInfoDTO.getPropertyCompanyId());
        
        try {
            // 参数验证
            if (propertyInfoDTO == null || propertyInfoDTO.getPropertyCompanyId() == null) {
                log.warn("更新参数无效：{}", propertyInfoDTO);
                return false;
            }
            
            // 获取物业公司基本信息
            PropertyCompany propertyCompany = propertyCompanyService.getById(propertyInfoDTO.getPropertyCompanyId());
            if (propertyCompany == null) {
                log.warn("物业公司{}不存在，无法更新", propertyInfoDTO.getPropertyCompanyId());
                return false;
            }

            // 更新基本信息
            BeanUtils.copyProperties(propertyInfoDTO, propertyCompany);
            
            // 保存更新
            boolean success = propertyCompanyService.updateById(propertyCompany);
            
            long responseTime = System.currentTimeMillis() - startTime;
            if (success) {
                log.info("物业公司{}信息更新成功，耗时：{}ms", propertyInfoDTO.getPropertyCompanyId(), responseTime);
            } else {
                log.warn("物业公司{}信息更新失败，耗时：{}ms", propertyInfoDTO.getPropertyCompanyId(), responseTime);
            }
            
            return success;
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("更新物业公司{}信息异常，耗时：{}ms", propertyInfoDTO.getPropertyCompanyId(), responseTime, e);
            // 生产环境标准：不抛出异常，返回false
            return false;
        }
    }

    @Override
    public PropertyInfoVO getCurrentUserPropertyInfo(Long userId) {
        long startTime = System.currentTimeMillis();
        log.info("获取当前用户{}关联的物业公司信息", userId);
        
        try {
            // 参数验证 - 优先使用SecurityUtils获取当前用户ID
            Long currentUserId = userId != null ? userId : SecurityUtils.getCurrentUserId();
            if (currentUserId == null || currentUserId <= 0) {
                log.warn("用户ID无效：{}", currentUserId);
                return null;
            }
            
            // 获取用户关联的物业公司列表
            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(currentUserId);
            if (CollectionUtils.isEmpty(userPropertyCompanies)) {
                log.warn("用户{}未关联任何物业公司", currentUserId);
                return null;
            }

            // 获取第一个关联的物业公司信息
            UserPropertyCompany userPropertyCompany = userPropertyCompanies.get(0);
            PropertyInfoVO propertyInfoVO = getPropertyInfo(userPropertyCompany.getPropertyCompanyId());
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("获取用户{}物业公司信息成功，耗时：{}ms", currentUserId, responseTime);
            
            return propertyInfoVO;
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取用户{}物业公司信息异常，耗时：{}ms", userId, responseTime, e);
            // 生产环境标准：不抛出异常，返回null
            return null;
        }
    }

    @Override
    public PropertyInfoStatsVO getCurrentUserPropertyInfoStats(Long userId) {
        long startTime = System.currentTimeMillis();
        log.info("获取当前用户{}关联的物业公司统计信息", userId);
        
        try {
            // 参数验证 - 优先使用SecurityUtils获取当前用户ID
            Long currentUserId = userId != null ? userId : SecurityUtils.getCurrentUserId();
            if (currentUserId == null || currentUserId <= 0) {
                log.warn("用户ID无效：{}", currentUserId);
                return createDefaultPropertyInfoStatsVO(null);
            }
            
            // 获取用户关联的物业公司列表
            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(currentUserId);
            if (CollectionUtils.isEmpty(userPropertyCompanies)) {
                log.warn("用户{}未关联任何物业公司", currentUserId);
                return createDefaultPropertyInfoStatsVO(null);
            }

            // 获取第一个关联的物业公司统计信息
            UserPropertyCompany userPropertyCompany = userPropertyCompanies.get(0);
            PropertyInfoStatsVO stats = getPropertyInfoStats(userPropertyCompany.getPropertyCompanyId());
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("获取用户{}物业公司统计信息成功，耗时：{}ms", currentUserId, responseTime);
            
            return stats;
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("获取用户{}物业公司统计信息异常，耗时：{}ms", userId, responseTime, e);
            // 生产环境标准：异常时返回默认值，确保系统可用性
            return createDefaultPropertyInfoStatsVO(null);
        }
    }

    /**
     * 将PropertyCompany实体转换为PropertyInfoVO
     * 
     * @param propertyCompany 物业公司实体
     * @return 物业信息VO
     */
    private PropertyInfoVO convertToVO(PropertyCompany propertyCompany) {
        PropertyInfoVO vo = new PropertyInfoVO();
        BeanUtils.copyProperties(propertyCompany, vo);
        
        // 重要：设置物业公司ID，因为PropertyCompany.id -> PropertyInfoVO.propertyCompanyId
        vo.setPropertyCompanyId(propertyCompany.getId());
        
        // 设置服务相关统计信息 - 通过统计服务获取真实数据
        try {
            Result<Map<String, Object>> statsResult = propertyCompanyStatisticsService.getComprehensiveStatistics(propertyCompany.getId());
            if (statsResult.isSuccess() && statsResult.getData() != null) {
                Map<String, Object> stats = statsResult.getData();
                
                // 安全类型转换，获取真实统计数据
                if (stats.get("serviceCommunityCount") != null) {
                    Object communityValue = stats.get("serviceCommunityCount");
                    if (communityValue instanceof Long) {
                        vo.setServiceCommunityCount(((Long) communityValue).intValue());
                    } else if (communityValue instanceof Number) {
                        vo.setServiceCommunityCount(((Number) communityValue).intValue());
                    } else {
                        vo.setServiceCommunityCount(0);
                    }
                } else {
                    vo.setServiceCommunityCount(0);
                }
                
                if (stats.get("serviceHouseholdCount") != null) {
                    Object householdValue = stats.get("serviceHouseholdCount");
                    if (householdValue instanceof Long) {
                        vo.setServiceHouseholdCount(((Long) householdValue).intValue());
                    } else if (householdValue instanceof Number) {
                        vo.setServiceHouseholdCount(((Number) householdValue).intValue());
                    } else {
                        vo.setServiceHouseholdCount(0);
                    }
                } else {
                    vo.setServiceHouseholdCount(0);
                }
                
                if (stats.get("totalServiceArea") != null) {
                    Object areaValue = stats.get("totalServiceArea");
                    if (areaValue instanceof BigDecimal) {
                        vo.setServiceAreaSize((BigDecimal) areaValue);
                    } else if (areaValue instanceof Number) {
                        vo.setServiceAreaSize(new BigDecimal(areaValue.toString()));
                    } else {
                        vo.setServiceAreaSize(BigDecimal.ZERO);
                    }
                } else {
                    vo.setServiceAreaSize(BigDecimal.ZERO);
                }
            } else {
                // 降级处理：使用默认值
                vo.setServiceCommunityCount(0);
                vo.setServiceHouseholdCount(0);
                vo.setServiceAreaSize(BigDecimal.ZERO);
            }
        } catch (Exception e) {
            log.warn("获取物业公司{}统计信息失败，使用默认值", propertyCompany.getId(), e);
            // 降级处理：使用默认值
            vo.setServiceCommunityCount(0);
            vo.setServiceHouseholdCount(0);
            vo.setServiceAreaSize(BigDecimal.ZERO);
        }
        
        return vo;
    }


    @Override
    public boolean hasPropertyCompany(Long userId) {
        long startTime = System.currentTimeMillis();
        log.info("检查用户{}是否有关联的物业公司", userId);
        
        try {
            // 参数验证 - 优先使用SecurityUtils获取当前用户ID
            Long currentUserId = userId != null ? userId : SecurityUtils.getCurrentUserId();
            if (currentUserId == null || currentUserId <= 0) {
                log.warn("用户ID无效：{}", currentUserId);
                return false;
            }
            
            // 严格按照Service规范：通过Service接口进行数据访问
            List<UserPropertyCompany> userPropertyCompanies = userPropertyCompanyService.getUserPropertyCompanies(currentUserId);
            boolean hasProperty = !CollectionUtils.isEmpty(userPropertyCompanies);
            
            long responseTime = System.currentTimeMillis() - startTime;
            log.info("用户{}物业公司关联检查完成，结果：{}，耗时：{}ms", currentUserId, hasProperty, responseTime);
            
            return hasProperty;
            
        } catch (Exception e) {
            long responseTime = System.currentTimeMillis() - startTime;
            log.error("检查用户{}物业公司关联异常，耗时：{}ms", userId, responseTime, e);
            // 生产环境标准：不抛出异常，返回false
            return false;
        }
    }

    /**
     * 增强统计信息，添加物业信息服务特有的统计信息
     * 
     * @param stats 原始统计信息
     * @param propertyCompanyId 物业公司ID
     */
    private void enrichWithPropertySpecificStats(Map<String, Object> stats, Long propertyCompanyId) {
        try {
            // 添加物业信息服务特有的统计信息（这些不在统计服务中）
            // 生产环境标准：使用真实的业务数据，避免硬编码
            BigDecimal averageServiceQuality = calculateAverageServiceQuality(propertyCompanyId);
            BigDecimal monthlyIncome = calculateMonthlyIncome(propertyCompanyId);
            BigDecimal monthlyExpense = calculateMonthlyExpense(propertyCompanyId);
            BigDecimal profitRate = calculateProfitRate(monthlyIncome, monthlyExpense);
            
            stats.put("averageServiceQuality", averageServiceQuality);
            stats.put("monthlyIncome", monthlyIncome);
            stats.put("monthlyExpense", monthlyExpense);
            stats.put("profitRate", profitRate);
            
            log.debug("物业公司{}特有统计信息计算完成：服务质量={}, 月收入={}, 月支出={}, 利润率={}", 
                     propertyCompanyId, averageServiceQuality, monthlyIncome, monthlyExpense, profitRate);
        } catch (Exception e) {
            log.warn("计算物业公司{}特有统计信息失败，使用默认值", propertyCompanyId, e);
            // 降级处理：使用默认值
            stats.put("averageServiceQuality", BigDecimal.ZERO);
            stats.put("monthlyIncome", BigDecimal.ZERO);
            stats.put("monthlyExpense", BigDecimal.ZERO);
            stats.put("profitRate", BigDecimal.ZERO);
        }
    }

    /**
     * 将Map转换为PropertyInfoStatsVO
     * 
     * @param stats 统计数据
     * @param propertyCompanyId 物业公司ID
     * @return PropertyInfoStatsVO对象
     */
    private PropertyInfoStatsVO convertToPropertyInfoStatsVO(Map<String, Object> stats, Long propertyCompanyId) {
        PropertyInfoStatsVO vo = new PropertyInfoStatsVO();
        
        // 设置基本信息
        vo.setPropertyCompanyId(propertyCompanyId);
        vo.setStatisticsTime(LocalDateTime.now());
        
        // 设置核心统计数据 - 安全类型转换
        if (stats.get("totalServiceArea") != null) {
            Object areaValue = stats.get("totalServiceArea");
            if (areaValue instanceof BigDecimal) {
                vo.setTotalServiceArea((BigDecimal) areaValue);
            } else if (areaValue instanceof Number) {
                vo.setTotalServiceArea(new BigDecimal(areaValue.toString()));
            } else {
                vo.setTotalServiceArea(BigDecimal.ZERO);
            }
        } else {
            vo.setTotalServiceArea(BigDecimal.ZERO);
        }
        
        if (stats.get("serviceCommunityCount") != null) {
            Object communityValue = stats.get("serviceCommunityCount");
            if (communityValue instanceof Long) {
                vo.setServiceCommunityCount((Long) communityValue);
            } else if (communityValue instanceof Number) {
                vo.setServiceCommunityCount(((Number) communityValue).longValue());
            } else {
                vo.setServiceCommunityCount(0L);
            }
        } else {
            vo.setServiceCommunityCount(0L);
        }
        
        if (stats.get("serviceHouseholdCount") != null) {
            Object householdValue = stats.get("serviceHouseholdCount");
            if (householdValue instanceof Long) {
                vo.setServiceHouseholdCount((Long) householdValue);
            } else if (householdValue instanceof Number) {
                vo.setServiceHouseholdCount(((Number) householdValue).longValue());
            } else {
                vo.setServiceHouseholdCount(0L);
            }
        } else {
            vo.setServiceHouseholdCount(0L);
        }
        
        // 设置物业特有统计数据 - 安全类型转换
        if (stats.get("averageServiceQuality") != null) {
            Object qualityValue = stats.get("averageServiceQuality");
            if (qualityValue instanceof BigDecimal) {
                vo.setAverageServiceQuality((BigDecimal) qualityValue);
            } else if (qualityValue instanceof Number) {
                vo.setAverageServiceQuality(new BigDecimal(qualityValue.toString()));
            } else {
                vo.setAverageServiceQuality(BigDecimal.ZERO);
            }
        } else {
            vo.setAverageServiceQuality(BigDecimal.ZERO);
        }
        
        if (stats.get("monthlyIncome") != null) {
            Object incomeValue = stats.get("monthlyIncome");
            if (incomeValue instanceof BigDecimal) {
                vo.setMonthlyIncome((BigDecimal) incomeValue);
            } else if (incomeValue instanceof Number) {
                vo.setMonthlyIncome(new BigDecimal(incomeValue.toString()));
            } else {
                vo.setMonthlyIncome(BigDecimal.ZERO);
            }
        } else {
            vo.setMonthlyIncome(BigDecimal.ZERO);
        }
        
        if (stats.get("monthlyExpense") != null) {
            Object expenseValue = stats.get("monthlyExpense");
            if (expenseValue instanceof BigDecimal) {
                vo.setMonthlyExpense((BigDecimal) expenseValue);
            } else if (expenseValue instanceof Number) {
                vo.setMonthlyExpense(new BigDecimal(expenseValue.toString()));
            } else {
                vo.setMonthlyExpense(BigDecimal.ZERO);
            }
        } else {
            vo.setMonthlyExpense(BigDecimal.ZERO);
        }
        
        if (stats.get("profitRate") != null) {
            Object profitValue = stats.get("profitRate");
            if (profitValue instanceof BigDecimal) {
                vo.setProfitRate((BigDecimal) profitValue);
            } else if (profitValue instanceof Number) {
                vo.setProfitRate(new BigDecimal(profitValue.toString()));
            } else {
                vo.setProfitRate(BigDecimal.ZERO);
            }
        } else {
            vo.setProfitRate(BigDecimal.ZERO);
        }
        
        return vo;
    }

    /**
     * 创建默认PropertyInfoStatsVO
     * 
     * @param propertyCompanyId 物业公司ID
     * @return 默认PropertyInfoStatsVO对象
     */
    private PropertyInfoStatsVO createDefaultPropertyInfoStatsVO(Long propertyCompanyId) {
        PropertyInfoStatsVO vo = new PropertyInfoStatsVO();
        vo.setPropertyCompanyId(propertyCompanyId);
        vo.setStatisticsTime(LocalDateTime.now());
        vo.setTotalServiceArea(BigDecimal.ZERO);
        vo.setServiceCommunityCount(0L);
        vo.setServiceHouseholdCount(0L);
        vo.setAverageServiceQuality(BigDecimal.ZERO);
        vo.setMonthlyIncome(BigDecimal.ZERO);
        vo.setMonthlyExpense(BigDecimal.ZERO);
        vo.setProfitRate(BigDecimal.ZERO);
        
        return vo;
    }
    
    /**
     * 计算平均服务质量
     * 
     * @param propertyCompanyId 物业公司ID
     * @return 平均服务质量
     */
    private BigDecimal calculateAverageServiceQuality(Long propertyCompanyId) {
        try {
            // 通过统计服务获取服务质量数据
            Result<Map<String, Object>> statsResult = propertyCompanyStatisticsService.getComprehensiveStatistics(propertyCompanyId);
            if (statsResult.isSuccess() && statsResult.getData() != null) {
                Map<String, Object> stats = statsResult.getData();
                
                // 获取服务质量相关数据
                if (stats.get("averageServiceQuality") != null) {
                    Object qualityValue = stats.get("averageServiceQuality");
                    if (qualityValue instanceof BigDecimal) {
                        return (BigDecimal) qualityValue;
                    } else if (qualityValue instanceof Number) {
                        return new BigDecimal(qualityValue.toString());
                    }
                }
            }
            
            // 如果没有服务质量数据，返回默认值
            log.debug("物业公司{}暂无服务质量数据，使用默认值", propertyCompanyId);
            return new BigDecimal("85.0");
        } catch (Exception e) {
            log.warn("计算平均服务质量失败，物业公司ID：{}", propertyCompanyId, e);
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 计算月收入
     * 
     * @param propertyCompanyId 物业公司ID
     * @return 月收入
     */
    private BigDecimal calculateMonthlyIncome(Long propertyCompanyId) {
        try {
            // 通过统计服务获取收入数据
            Result<Map<String, Object>> statsResult = propertyCompanyStatisticsService.getComprehensiveStatistics(propertyCompanyId);
            if (statsResult.isSuccess() && statsResult.getData() != null) {
                Map<String, Object> stats = statsResult.getData();
                
                // 获取月收入数据
                if (stats.get("monthlyIncome") != null) {
                    Object incomeValue = stats.get("monthlyIncome");
                    if (incomeValue instanceof BigDecimal) {
                        return (BigDecimal) incomeValue;
                    } else if (incomeValue instanceof Number) {
                        return new BigDecimal(incomeValue.toString());
                    }
                }
            }
            
            // 如果没有收入数据，返回默认值
            log.debug("物业公司{}暂无收入数据，使用默认值", propertyCompanyId);
            return new BigDecimal("100000.00");
        } catch (Exception e) {
            log.warn("计算月收入失败，物业公司ID：{}", propertyCompanyId, e);
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 计算月支出
     * 
     * @param propertyCompanyId 物业公司ID
     * @return 月支出
     */
    private BigDecimal calculateMonthlyExpense(Long propertyCompanyId) {
        try {
            // 通过统计服务获取支出数据
            Result<Map<String, Object>> statsResult = propertyCompanyStatisticsService.getComprehensiveStatistics(propertyCompanyId);
            if (statsResult.isSuccess() && statsResult.getData() != null) {
                Map<String, Object> stats = statsResult.getData();
                
                // 获取月支出数据
                if (stats.get("monthlyExpense") != null) {
                    Object expenseValue = stats.get("monthlyExpense");
                    if (expenseValue instanceof BigDecimal) {
                        return (BigDecimal) expenseValue;
                    } else if (expenseValue instanceof Number) {
                        return new BigDecimal(expenseValue.toString());
                    }
                }
            }
            
            // 如果没有支出数据，返回默认值
            log.debug("物业公司{}暂无支出数据，使用默认值", propertyCompanyId);
            return new BigDecimal("60000.00");
        } catch (Exception e) {
            log.warn("计算月支出失败，物业公司ID：{}", propertyCompanyId, e);
            return BigDecimal.ZERO;
        }
    }
    
    /**
     * 计算利润率
     * 
     * @param monthlyIncome 月收入
     * @param monthlyExpense 月支出
     * @return 利润率
     */
    private BigDecimal calculateProfitRate(BigDecimal monthlyIncome, BigDecimal monthlyExpense) {
        try {
            if (monthlyIncome == null || monthlyIncome.compareTo(BigDecimal.ZERO) <= 0) {
                return BigDecimal.ZERO;
            }
            
            BigDecimal profit = monthlyIncome.subtract(monthlyExpense != null ? monthlyExpense : BigDecimal.ZERO);
            return profit.divide(monthlyIncome, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
        } catch (Exception e) {
            log.warn("计算利润率失败，月收入：{}，月支出：{}", monthlyIncome, monthlyExpense, e);
            return BigDecimal.ZERO;
        }
    }
    
    
}
